package com.taglab.chic.search;

import java.util.Iterator;
import java.util.Collection;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;

/**
 * Holds a search result set.
 *  
 * @author Markus Kobler
 */
public class SearchResults implements Iterable<Hit> {

  private final Query query;

  private final int totalHits;

  private final List<Hit> hits;

  private Date generated;

  public SearchResults(Query query, Collection<Hit> hits, int totalHits, Date generated) {
    this.query = query;
    this.hits = new ArrayList<Hit>(hits);
    this.totalHits = totalHits;
    this.generated = generated == null ? new Date() : generated;
  }

  public Query getQuery() {
    return query;
  }

  public String getSearchTerms() {
    return query.getSearchTerms();
  }

  public int getStartPage() {
    return query.getStartPage();
  }

  public int getItemsPerPage() {
    return query.getItemsPerPage();
  }
  
  public List<Hit> getHits() {
    return Collections.unmodifiableList(hits);
  }

  public int getTotalHits() {
    return totalHits;
  }

  public int getTotalPages() {
    if( totalHits == 0 ) return 0;
    return (int)Math.ceil(totalHits / getItemsPerPage());
  }

  public Date getGenerated() {
    return generated;
  }

  public Iterator<Hit> iterator() {
    return getHits().iterator();
  }

  @Override
  public String toString() {
    final StringBuilder sb = new StringBuilder();
    sb.append("SearchResults");
    sb.append("{query=").append(query);
    sb.append(", generated=").append(generated);
    sb.append(", totalHits=").append(totalHits);
    sb.append(", hits:\n");
    int count = 1;
    for( Hit hit : hits) {
      sb.append(count++).append(":").append(hit.toLongString()).append("\n");
    }
    sb.append('}');
    return sb.toString();
  }

}
